<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 用户_控制器
 * 	进入该控制器需用户已登录
 * @property User_mdl $users
 * @property UserORM  $user
 */
class User extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load->model('User_mdl','users');
		$this->user = parent::getLoginUser();
	}
	/**
	 * API:用户基本信息
	 */
	public function index(){
		debug('currentPhoneID',$this->user->currentPhoneID);
		$this->apiOutput->put('user', $this->user->getBaseInfo())->out();
	}
	/**
	 * API:绑定手机
	 */
	public function bind_phone(){
		$input = check_input($_REQUEST,array('phone','captcha'));
		if( !$input ){
			$this->apiOutput->errorInput();
		}
		
		if( empty($input['phone']) ){
			$this->apiOutput->error('手机号码格式不正确',-2);
		}
		
		$phone = $this->user->phone;
		if( !empty($phone) ){
		    $this->apiOutput->error('您已经绑定过手机,不允许修改',-1);
		}
		
		$this->load->library('PhoneCaptcha',NULL,'captcha');
		if( !$this->captcha->check($input['phone'],$input['captcha']) ){
		    $this->apiOutput->error('验证码错误',-3);
		}
		$where = array('phone'=>$input['phone']);
		$user  = $this->users->findOne($where);
		if( !empty($user) ){
		   $this->apiOutput->put('status', 0)
							->error('该手机已注册,不可以与你绑定',-4);
		}
		
		$this->user->phone = $input['phone'];
		if( $this->user->update() ){
		    $this->apiOutput->put('msg', '绑定手机成功')->put('status',1)->out();
		}else{
		    $this->apiOutput->errorSystem();
		}
	}
	/**
	 * 绑定微信
	 */
	public function bind_wechat(){
		$input = check_input ( $_REQUEST, array (
				'wxOpenID',//微信openID
				'nickname',//微信昵称
				'headImgUrl',//微信头像URL
				'wxUnionID',//微信unionID
		) );
		if( !$input ){
		    $this->apiOutput->errorInput();
		}
		
		$weChat = $this->user->wxOpenID;
		if( !empty($weChat) ){
		    $this->apiOutput->error('您已经绑定过微信,不允许修改',-11);
		}
		
		$where = array('wxOpenID'=>$input['wxOpenID']);
		$wxUser = $this->users->findOne($where);
		if( !empty($wxUser) ){
			$this->apiOutput->put('status', 0)
							->error('该微信已注册,不可与你绑定!',-4);
		}
		$this->user->wxOpenID    = $input['wxOpenID'];
		$this->user->nickname    = $input['nickname'];
		$this->user->headImgUrl  = $input['headImgUrl'];
		$this->user->wxOpenID    = $input['wxOpenID'];
		$this->user->wxUnionID   = $input['wxUnionID'];
		
		if( $this->user->update() ){
		    $this->apiOutput->put('msg', '绑定微信成功')->put('status', 1)->out();
		}else{
		    $this->apiOutput->errorSystem();
		}
		
	}
	
	public function combine(){
		$userID = (int)$this->input->post_get('userID');
		$type   = (int)$this->input->post_get('type');
		
		$otherUser = $this->users->findOneByID($userID);
		if( empty($otherUser) ){
			$this->apiOutput->error('无该用户',-201);
		}
		switch ($type) {
			case 1:// 手机用户合并微信用户
				$pUser = &$this->user;
				$wxUser = &$otherUser;
				if ( !empty($pUser->wxOpenID) ) {
					$this->apiOutput->error('你已绑定过微信,不能合并其他微信账户',-203);
				}
				
				if ( !empty($wxUser->phone) ) {
					$this->apiOutput->error('你要合并的微信账户已绑定其他手机,不能进行合并',-204);
				}
				break;
			case 2:// 微信用户合并手机用户
				$wxUser = &$this->user;
				$pUser  = &$otherUser; 
				if( ! empty($wxUser->phone) ){
					$this->apiOutput->error('你已绑定过手机,不能合并其他手机账户',-205);
				}
				
				if( ! empty($pUser->wxOpenID) ){
					$this->apiOutput->error('你要合并的手机账户已绑定其他微信,不能进行合并',-206);
				}
				break;
			default:
				$this->apiOutput->errorInput();
				break;
		}
		if( empty($pUser->phone) ){
			$this->apiOutput->error('你未绑定手机',-201);
		}
		if( empty($wxUser->wxOpenID) ){
			$this->apiOutput->error('你未绑定微信',-202);
		}
		// ==== 选择保留的主账户 =====
		// 如果微信账户的 余额,累计充值,累计消费,累计赠送 等纪录有一项不为空
		// 则选择微信账户为主账户
		// 否则选择手机账户为主账户
		$moneyKeys = array (
				'balance',
				'rechargeTotal',
				'buyTotal',
				'presrent'
		);
		$mainUser = $pUser;
		$delUser  = $wxUser;
		foreach ( $moneyKeys as $key ) {
			if ($wxUser->{$key} != 0) {
				$mainUser = $wxUser;
				$delUser = $pUser;
				break;
			}
		}
		$user = $this->users->combine($mainUser, $delUser);
		if (empty($user)) {
			$this->apiOutput->errorSystem();
		}
		$user->afterLogin( $this->user->currentPhoneID );
		$this->apiOutput->put('user',$user->getBaseInfo())->out();
	}
	
	
	/**
	 * 更新基本资料
	 */
	public function update(){

		$input = check_input($_REQUEST);
		foreach ($input as $field => $val) {
			if( $val==='' ){
				continue;
			}
			switch ($field) {
				// ----昵称----
				case 'nickname':
					if( strLength($val) > 12 ){
						$this->apiOutput->error('用户昵称不得超过12个字符',-21);
					}
					if( empty($val) ){
						$this->apiOutput->error('用户昵称不得为空',-21);
					}
					$this->user->nickname = $val;
					break;
			}
		}
		
		if( $this->user->update() ){
			$this->apiOutput->put('user', $this->user->getBaseInfo());
		}else{
			$this->apiOutput->errorSystem();
		}
		
	}
	/**
	 * 上传头像
	 */
	public function upload_headimg(){

		$dir = 'upload/userHeadImg/';
		$file = $this->user->id.'_'.time();
		$config = array(
				'upload_path'=>FCPATH.$dir,
				'allowed_types'=>'gif|jpg|png|jpeg',
				'max_size'=>1024,
				'file_name'=>$file,
		);
		
		if( ! is_dir($config['upload_path']) ){
			mkdir($config['upload_path']);
		}
		
		$this->load->library('upload',$config);
		if( ! $this->upload->do_upload('imgFile') ){
			// 上传失败:
			$msg = strip_tags( $this->upload->display_errors() );
			debug('upload_error',$msg);
			$this->apiOutput->error('头像上传失败:'.$msg,-41);
		}else{
			// 上传成功
			$data = $this->upload->data();
			$host = 'http://'.$_SERVER['SERVER_NAME'];
			$url = $dir.$data['orig_name'];
			// 更新到数据库
			$oldPortrait = $this->user->headImgUrl;
			$this->user->headImgUrl = $url;
			if( $this->user->update() ){
				// 更新成功:删除旧头像的本地图片
				if( ! empty($oldPortrait) ){
					$info = parse_url($oldPortrait);
					$filepath = FCPATH.$info['path'];
					if( file_exists($filepath) ){
						unlink($filepath);
					}
				}
				// 输出信息
				$out['msg'] = '上传头像成功';
				$out['url'] = base_url($url);
				$this->apiOutput->out($out);
			}else{// 更新到数据库失败:
				$this->apiOutput->errorSystem();
			}
		}
	}
	
	public function logout(){
		$res = $this->user->logout();
		$this->apiOutput->msg('退出成功!');
	}
	
	
}
